#! /bin/sh

id="`basename \"$0\"`"
loc="`dirname \"$0\"`"
hook_funcs="$loc/erlrc-hooks"

test -r "$hook_funcs" || {
  echo "$id: error: can't read file '$hook_funcs'" 1>&2
  exit 2
}

. "$hook_funcs"

erlrc_start () {
  local package="$1"
  local version="$2"
  local dir="$3"
  local node="$4"
  local cookie="$5"

  printf " (%s) " "$node"

  if test "x$dir" = "x\0"
    then
      erlrc_remote_eval "$node" "$cookie"                           \
        "case erlrcdynamic:start ('$package', \"$version\") of
           R when (R =:= already_running) or 
                  (R =:= included) or 
                  (R =:= started) or 
                  (R =:= started_included_stopped) ->
              R
         end" || {
        echo 
        exit 1
      }
    else
      erlrc_remote_eval "$node" "$cookie"                           \
        "case erlrcdynamic:start ('$package', \"$version\", \"$dir\") of
           R when (R =:= already_running) or 
                  (R =:= included) or 
                  (R =:= started) or 
                  (R =:= started_included_stopped) ->
              R
         end" || {
        echo 
        exit 1
      }
    fi
}

usage () {
  echo "usage: $id package version [ dir ]" 1>&2
  exit 2
}

#---------------------------------------------------------------------
#                                Main                                 
#---------------------------------------------------------------------

test -n "$1" || { usage; }
test -n "$2" || { usage; }

package="$1"
version="$2"
dir=${3-"\0"}

printf "%s: Starting '%s':" "$id" "$package"

erlrc_node_foreach erlrc_start "$package" "$version" "$dir" && echo
